package com.shebei.api.equipment_api_test.vueController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shebei.api.equipment_api_test.dao.ApiNameQueryDAO;
import com.shebei.api.equipment_api_test.dao.UserCaseWoDAO;
import com.shebei.api.equipment_api_test.model.*;
import com.shebei.api.equipment_api_test.model.responseModel.*;
import com.shebei.api.equipment_api_test.service.UserCaseExcute;
import com.shebei.api.equipment_api_test.service.vueservice.PerformanceService;
import com.shebei.api.equipment_api_test.service.vueservice.UserCaseService;
import com.shebei.api.equipment_api_test.service.vueservice.VueCaseExcute;
import com.shebei.api.equipment_api_test.thread.CaseExcuteRunnable;
import com.shebei.api.equipment_api_test.utils.GetLinuxTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


@RestController
@RequestMapping("usercase")
public class LoginController {

    @Autowired
    UserCaseWoDAO userCaseWoDAO;


    @Autowired
    GetLinuxTime getLinuxTime;

    @Autowired
    ApiNameQueryDAO apiNameQueryDAO;

    @Autowired
    UserCaseExcute userCaseExcute;
    @Autowired
    VueCaseExcute vueCaseExcute;

    @Autowired
    UserCaseService userCaseService;

    @Autowired
    PerformanceService performanceService;


//    @RequestMapping(value="vue-admin-template/user/login",method = RequestMethod.POST)
//    public String  getTest(@RequestParam("username") String userName,@RequestParam("password") String password){
//        ResModel resModel= new ResModel();
//        TokenModel tokenModel = new TokenModel();
//
//        tokenModel.setToken("admin-token");
//
//        resModel.setCode(20001);
//
//        resModel.setToken(tokenModel);
//        String response = JSONArray.toJSONString(resModel);
//
//        return response;
//
//    }

    @RequestMapping(value="user/login",method = RequestMethod.POST)
    public JSONObject getTestAPi(HttpServletRequest request, @RequestBody LoginController loginController){
        ResModel resModel= new ResModel();
        TokenModel tokenModel = new TokenModel();

        tokenModel.setToken("admin-token");

        resModel.setCode(20000);

        resModel.setData(tokenModel);
        String response = JSON.toJSONString(resModel);
        JSONObject responses = (JSONObject) JSONObject.parseObject(response);

        return responses;

    }

    @RequestMapping(value="user/info",method = RequestMethod.GET)
    public JSONObject getInfo(@RequestParam("token") String token){

        String response="{\"code\":20000,\"data\":{\"roles\":[\"admin\"],\"introduction\":\"I am a super administrator\",\"avatar\":\"https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif\",\"name\":\"Super Admin\"}}";
        JSONObject responses = (JSONObject) JSONObject.parseObject(response);

        return responses;

    }


    @RequestMapping(value="table/list",method = RequestMethod.GET)
    public ResModel getTableList(@RequestParam("caseName")  String caseName,
                                 @RequestParam("apiName")  String apiName,
                                 @RequestParam("apiAddress")  String apiAddress,
                                 @RequestParam("scene")  String scene,
                                 @RequestParam("module")  String module ,
                                 @RequestParam("apiGroup")  String apiGroup ,
                                 @RequestParam("adptiveVersion")  String adptiveVersion ){
        ResModel resModel= new ResModel();
        UserCaseWoWithBLOBs record=new UserCaseWoWithBLOBs();
        record.setUserCaseName(caseName);
        record.setApiName(apiName);
        record.setApiValue(apiAddress);
        record.setScene(scene);
        record.setModule(module);
        record.setApiGroup(apiGroup);
        record.setAdaptiveVersion(adptiveVersion);
         deleteSpace(record);
        List<UserCaseGroup> list= userCaseWoDAO.selectCasesBySceneDes(record);
        resModel.setCode(20000);
         JSONArray response= (JSONArray) JSONArray.toJSON(list);
        resModel.setData(response);
        return resModel;

    }

    @RequestMapping(value="table/reRange",method = RequestMethod.POST)
    public ResModel casesRerange(
                                 @RequestParam("scene")  String scene,
                                 @RequestParam("module")  String module ){


        ResModel resModel= new ResModel();
//        UserCaseWoWithBLOBs record=new UserCaseWoWithBLOBs();
//
//        record.setScene(scene);
//        record.setModule(module);
//
//        List<UserCaseGroup> list= userCaseWoDAO.selectCasesBySceneDes(record);
//               int count=list.size();
//       for (UserCaseWoWithBLOBs iter:list){
//           int temp=iter.getExcuteSequence();
//           iter.setExcuteSequence(count);
//           userCaseWoDAO.updateByPrimaryKeyWithBLOBs(iter);
//           System.out.println("temp:"+temp +" 改为："+count);
//           count--;
//
//
//       }
        userCaseService.caseReRange(module,scene);

        resModel.setCode(20000);
        resModel.setData("success");
        return resModel;

    }

   // selectCasesBySceneDesDeleted

    @RequestMapping(value="table/list/deleted",method = RequestMethod.GET)
    public ResModel getTableListDeleted(@RequestParam("caseName")  String caseName,
                                 @RequestParam("apiName")  String apiName,
                                 @RequestParam("apiAddress")  String apiAddress,
                                 @RequestParam("scene")  String scene,
                                 @RequestParam("module")  String module ,
                                 @RequestParam("apiGroup")  String apiGroup ,
                                 @RequestParam("adptiveVersion")  String adptiveVersion ){
        ResModel resModel= new ResModel();
        UserCaseWoWithBLOBs record=new UserCaseWoWithBLOBs();
        record.setUserCaseName(caseName);
        record.setApiName(apiName);
        record.setApiValue(apiAddress);
        record.setScene(scene);
        record.setModule(module);
        record.setApiGroup(apiGroup);
        record.setAdaptiveVersion(adptiveVersion);
        deleteSpace(record);
        List<UserCaseGroup> list= userCaseWoDAO.selectCasesBySceneDesDeleted(record);
        resModel.setCode(20000);
        JSONArray response= (JSONArray) JSONArray.toJSON(list);
        resModel.setData(response);
        return resModel;

    }


    @RequestMapping(value="table/edit",method = RequestMethod.POST)
    public JSONObject userCaseEdit(HttpServletRequest request, @RequestBody UserCaseWoWithBLOBs userCaseWo){

        deleteSpace(userCaseWo);
        userCaseWo= getApiValue( userCaseWo);
       int updateRes= userCaseWoDAO.updateByPrimaryKeySelective(userCaseWo);
        ResModel resModel= new ResModel();


        resModel.setCode(20000);
        resModel.setData(updateRes);

        String response = JSON.toJSONString(resModel);
        JSONObject responses = (JSONObject) JSONObject.parseObject(response);

        return responses;

    }


    @RequestMapping(value="table/excute",method = RequestMethod.POST)
    public JSONObject userCaseExcute(@RequestParam("id")  Integer id,@RequestParam("env")  String env){


        ApiResModel result=  userCaseExcute.vueExcuteOneCase(id,env);
        ResModel resModel= new ResModel();


        resModel.setCode(20000);
        resModel.setData(result);

        String response = JSON.toJSONString(resModel);
        JSONObject responses = (JSONObject) JSONObject.parseObject(response);

        return responses;

    }


    @RequestMapping(value="table/cases/isDeleteUpadte",method = RequestMethod.POST)
    public JSONObject userCaseDelete(@RequestParam("isDelete")  Integer isDelete,@RequestParam("adaptiveVersion")  String adaptiveVersion){
        ResModel resModel= new ResModel();


        resModel.setCode(20000);
        if(adaptiveVersion==null||adaptiveVersion.equals("")){
            resModel.setData("不能选所有的组，请选择一个组");
        }else {
            UserCaseWo userCaseWo=new UserCaseWo();

            userCaseWo.setAdaptiveVersion(adaptiveVersion);
            userCaseWo.setIsDelete(isDelete);
            int updateRes= userCaseWoDAO.updateDelete(userCaseWo);

            if(updateRes>0){
                resModel.setData("组更新成功");
            }else {
                resModel.setData("组更新失败");
            }

        }


        String response = JSON.toJSONString(resModel);
        JSONObject responses = (JSONObject) JSONObject.parseObject(response);

        return responses;

    }


    @RequestMapping(value="performance/excute",method = RequestMethod.POST)
    public JSONObject performanceSingleExcute(HttpServletRequest request, @RequestBody ConcurrentModel concurrentModel){
           Integer id=concurrentModel.getId();
           String env=concurrentModel.getEnv();
           Integer users=concurrentModel.getUsers();
           Integer timeValue= concurrentModel.getTimeValue();

           String module=concurrentModel.getModule();

       String res=  performanceService.excuteSingle( id,  env, users, timeValue);
        ResModel resModel= new ResModel();


        resModel.setCode(20000);

        resModel.setData(res);
        if(res.equals("")){
            resModel.setData("性能服务器没有响应");
        }
        String response = JSON.toJSONString(resModel);
        JSONObject responses = (JSONObject) JSONObject.parseObject(response);

        return responses;

    }

    @RequestMapping(value="performance/scene/excute",method = RequestMethod.POST)
    public JSONObject performanceSceneExcute(HttpServletRequest request, @RequestBody PerForSceneModel perForSceneModel){


        String result=  performanceService.performanceScne(perForSceneModel);
        ResModel resModel= new ResModel();


        resModel.setCode(20000);
        resModel.setData(result);

        String response = JSON.toJSONString(resModel);
        JSONObject responses = (JSONObject) JSONObject.parseObject(response);

        return responses;

    }
    @RequestMapping(value="table/copy",method = RequestMethod.POST)
    public JSONObject userCaseCopy(HttpServletRequest request, @RequestBody UserCaseWoWithBLOBs userCaseWo){

        deleteSpace(userCaseWo);
       // String time= getLinuxTime.getTime();
//        String userCaseName=userCaseWo.getUserCaseName()+"_"+time;
        String userCaseName=userCaseWo.getUserCaseName();
        userCaseWo.setUserCaseName(userCaseName);
        userCaseWo= getApiValue( userCaseWo);
        userCaseWo.setId(null);
       int insertRes= userCaseWoDAO.insert(userCaseWo);
        ResModel resModel= new ResModel();


        resModel.setCode(20000);
        resModel.setData(insertRes);

        String response = JSON.toJSONString(resModel);
        JSONObject responses = (JSONObject) JSONObject.parseObject(response);

        return responses;

    }

    @RequestMapping(value="scene/casesExcute",method = RequestMethod.POST)
    public JSONObject casesExcute(@RequestParam("scene")  String scene,
                                  @RequestParam("env")  String env,
                                  @RequestParam("module")  String module){


        ResModel resModel= new ResModel();
       // String result=vueCaseExcute.sceneExcute(scene, module, env);
        CaseExcuteRunnable caseExcuteRunnable=new CaseExcuteRunnable( scene, env, module);
        Thread thread1=new Thread(caseExcuteRunnable);
        thread1.start();

        resModel.setCode(20000);
        if(scene.equals("")){
            resModel.setData("开始执行模块："+module+"的所有场景，请到测试结果页面查看");
        }else {
            resModel.setData("开始执行模块："+module+"；场景："+scene+"，请到测试结果页面查看");
        }


        String response = JSON.toJSONString(resModel);
        JSONObject responses = (JSONObject) JSONObject.parseObject(response);

        return responses;

    }

    @RequestMapping(value="cases/group",method = RequestMethod.POST)
    public JSONObject casesGrpsList(
                                  @RequestParam("apiGroup")  String apiGroup,
                                  @RequestParam("module")  String module,
                                  @RequestParam("scene")  String scene){


        ResModel resModel= new ResModel();
          List<NavigateName> casesGroups=userCaseService.getCaseGroup(module,apiGroup,scene);

        resModel.setCode(20000);

        resModel.setData(casesGroups);


        String response = JSON.toJSONString(resModel);
        JSONObject responses = (JSONObject) JSONObject.parseObject(response);

        return responses;

    }

    private UserCaseWoWithBLOBs getApiValue(UserCaseWoWithBLOBs record){
        String apiName=record.getApiName();
        if(apiName==null||apiName.equals("")){
            return  record;
        }
        ApiNameQuery apiNameQuery=apiNameQueryDAO.selectByName(apiName);
        if(apiNameQuery!=null){
            record.setApiValue(apiNameQuery.getApiValue());
            record.setRequestType(apiNameQuery.getRequestType());
            record.setApiGroup(apiNameQuery.getApiGroup());
        }else {
            record.setApiValue("");
            record.setRequestType("");
        }
        return record;
    }

    public void deleteSpace(UserCaseWoWithBLOBs var) {
        if (var.getApiName() != null) {
            var.setApiName(var.getApiName().trim());
        }
        if (var.getModule() != null) {
            var.setModule(var.getModule().trim());
        }
        if (var.getUserCaseName() != null) {
            var.setUserCaseName(var.getUserCaseName().trim());
        }
        if (var.getScene() != null) {
            var.setScene(var.getScene().trim());
        }
        if (var.getCheckPath() != null) {
            var.setCheckPath(var.getCheckPath().trim());
        }

        if (var.getParameterSavePath() != null) {
            var.setParameterSavePath(var.getParameterSavePath().trim());
        }
        if (var.getRequestBody() != null) {
            var.setRequestBody(var.getRequestBody().trim());
        }
        if (var.getApiValue() != null) {
            var.setApiValue(var.getApiValue().trim());
        }
        if (var.getRequestType() != null) {
            var.setRequestType(var.getRequestType().trim());
        }
        if (var.getAdaptiveVersion() != null) {
            var.setAdaptiveVersion(var.getAdaptiveVersion().trim());
        }
        if (var.getApiGroup() != null) {
            var.setApiGroup(var.getApiGroup().trim());
        }


    }


}
